<?php

/**
 * Created by PhpStorm.
 * User: allen_ios
 * Date: 17/6/12
 * Time: 下午6:47
 */
class ZduStyyApiAction extends BaseAction
{
      public  $accountId;
      public  $mRestaurantGoods;
      private $mRestaurantInfo;
      private $mGoodsCategory;
      private $mRestaurant;
      private $mWeekRelation;
      private $mWindow;
      private $mGoods;
      private $resId;
      public $url;
    public function _initialize()
    {
        $this->mRestaurant = D('Base/Restaurantstyy');
        $this->mRestaurantInfo = D('Base/RestaurantstyyInfo');
        $this->mWindow = D('Base/RestaurantstyyWindow');
        $this->mGoodsCategory = D('Base/RestaurantstyyGoodsCategory');
        $this->mWeekRelation = D('Base/RestaurantstyyWeekRelation');
        $this->mGoods = D('Base/RestaurantstyyGoods');
        $this->accountId = 60;
        $this->resId = $this->mRestaurant->where(array('account_id'=>$this->accountId))->getField('res_id');
    }


    /**
     * http请求
     * @param $url 请求地址
     * @param null $postFields 请求参数
     * @return mixed
     * @throws Exception
     */
    public function curl($url = '', $postParams= null)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //超时时间
        curl_setopt($ch, CURLOPT_TIMEOUT,30);
        curl_setopt($ch, CURLOPT_HEADER,0);
        // post提交数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // post的变量
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postParams);
        if(!is_array($postParams)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($postParams)
            ));
        }
        $output = json_decode(curl_exec($ch),true);
        curl_close($ch);
        //打印获得的数据
        return $output;
    }
    

    /**
     * 获取餐厅信息接口
     */
    public function doRestaurant($canteen_id=''){

        if(!$canteen_id){
            $canteen_id = $this->_request('id');
        }

        $url = 'http://smart.zjulab.com:82/d/getCanteenInfo.xl?canteen_ids='.$canteen_id;

        $data = $this->curl($url);

        $str = array();
        if($data['code']==200){
            foreach($data['data'] as $k=>$v){
                $info = array(
                'restaurant_id'   => $v['id'], //校联餐厅id
                'res_id'          => $this->resId,
                'restaurant_name' => $v['name'],
                'restaurant_desc' => $v['description'],
                'address'         => $v['addr'],
                'mobile'          => $v['phone'],
                'create_time'     => time(),
//                'logo_url'        => $v['picture'],
//                'time1'           => $v['times1'],
//                'time2'           => $v['times11'],
//                'time3'           => $v['times2'],
//                'time4'           => $v['times22'],
//                'time5'           => $v['times3'],
//                'time6'           => $v['times33'],
                'id'              => $v['id'], //校联餐厅id
                );
                $res = $this->mRestaurantInfo->where(array('restaurant_id'=>$v['id']))->find();
                if($res){
                    $this->mRestaurantInfo->save($info);
                }else{
                    $this->mRestaurantInfo->add($info);
                }
                $str[] = $v['id'];
            }

            foreach($str as $k=>$v){
                $this->doWindow($v);
            }

        }
    }

    /**
     * 获取档口信息接口
     */
    public function doWindow($restaurantIds){ //参数不连贯给一个默认值  正式服不需要默认值
//        $url = 'http://smart.zjulab.com:82/d/getDangKouInfo.xl?canteen_id='.$restaurantIds;
        $url = 'http://10.15.150.182:82/d/getDangKouInfo.xl?canteen_id='.$restaurantIds;
        $data = $this->curl($url);

        $str = '';
//        $list = $this->mWindow->where(array('cut_off'=>0,'res_id'=>$this->resId))->getField('window_id,restaurant_id');
        if($data['code']==200){
            foreach($data['data'] as $k=>$v){
                $info = array(
                    'window_id'=>$v['id'],
                    'restaurant_id'=>$restaurantIds ,
                    'window_name'=>$v['name'],
                    'create_time'=>time(),
                    'id'=>$v['id'], //校联档口id
                    'pid'=>$v['pid'], //校联餐厅id标识
                );
                $res = $this->mWindow->where(array('window_id'=>$v['id']))->find();
                if($res){
                    $this->mWindow->save($info);
                }else{
                    $this->mWindow->add($info);
                }
                $str .= $v['id'].',';
            }

//            $windowIds = substr($str,0,strlen($str)-1);
//
//            $this->doCategory($restaurantIds,$windowIds);
        }
    }


    /**
     * @param int $window_id 档口id
     * @throws Exception 获取分类菜品的信息
     */
    public function doCategory($restaurantIds='',$windowIds=''){
//        $url = "http://smart.zjulab.com:82/d/getDkStockType.xl?canteen_ids=".$windowIds;
        $url = "http://10.15.150.182:82/d/getDkStockType.xl?canteen_ids=".$windowIds;
        $data = $this->curl($url);

//        echo "<pre>";
//        var_dump($data);exit;
        $restaurant = $this->mWindow->where(array('cut_off'=>0,'res_id'=>$this->resId))->getField('window_id,restaurant_id');
        $sort = 1; //排序
        if($data['code']==200){
            foreach($data['data'] as $k=>$v){
                $info = array(
                    'category_id'=>$v['typeCode'],
                    'res_id'=>$this->resId,
                    'restaurant_id'=>$restaurant[$v['dangKouId']],
                    'window_id'=>$v['dangKouId'],
                    'category_name'=>$v['typeName'],
                    'create_time'=>time(),
                    'cut_off'=>0,
                    'typeId'=>$v['typeCode'], //菜品分类id
                    'dangKouId'=>$v['dangKouId'], //档口id
                );
                $res = $this->mGoodsCategory->where(array('category_id'=>$v['typeCode']))->find();
                if($res){
                    $this->mGoodsCategory->save($info);
//                    $sql = "UPDATE gc_restaurantstyy_goods_category SET category_id=".$info['category_id'].",res_id=".$this->resId.",
//                    restaurant_id=".$info['restaurant_id'].",window_id=".$info['window_id'].",category_name='".$info['category_name']."',
//                    create_time=".$info['create_time'].",dangKouId=".$info['dangKouId'].",typeId=".$info['typeId']."
//                    WHERE category_id=".$info['category_id']." and window_id=".$info['window_id'];
//                    M()->query($sql);
                }else{
                    $info['sort'] = $sort;
                    $sort++;
                    $this->mGoodsCategory->add($info);
                }
            }
//            $time = date('Y-m-d',time());
//
//            $this->doGoods($restaurantIds,$windowIds,$time);
        }
    }



    /***
     * 获取菜品接口
     */
    public function doGoods($restaurantIds,$windowIds,$time,$type='')
    {
        if($type != 1){
            $windowIds = explode(',', $windowIds);
        }

        foreach ($windowIds as $key => $value) {
            // $url = 'http://smart.zjulab.com:82/r/platesettingsV2.xl?id=' . $restaurantIds . '&shopids=' . $value . '&d=' . $time;
//            $url = 'http://smart.zjulab.com/apis.php?c=Z_braindisc&a=platesettingsV2&id=' . $restaurantIds . '&shopids=' . $value . '&d=' . $time;
            $url = 'http://10.15.150.182/apis.php?c=Z_braindisc&a=platesettingsV2&id=' . $restaurantIds . '&shopids=' . $value . '&d=' . $time;
//            $url = 'http://smart.zjulab.com:82/r/platesettingsV2.xl?id=' . $restaurantIds . '&shopids=50&d=' . $time;
            $data = $this->curl($url);

            $str = '';
            // $restaurant = $this->mWindow->where(array('cut_off' => 0, 'res_id' => $this->resId))->getField('window_id,restaurant_id');
            //|| $data['code'] == -2 || $data['code'] == -1
            if ($data['code'] == 200&&!empty($data['data'])) {

                foreach ($data['data'] as $k => $v) {
                    foreach ($v as $k1 => $v1) {
                        $info = array(
                            'goods_id' => $v1['stockId'],
                            'res_id' => $this->resId,
                            'restaurant_id' => $restaurantIds,
                            'category_id' => $v1['cate'], //分类id
                            'goods_name' => $v1['name'],
                            'price' => $v1['price'],
                            'goods_logo' => $v1['pic'],
                            'goods_sum' => $v1['amount'],
                            'create_time' => time(),
                            'show' => 1,
                            'cut_off' => 0,
                            'cate' => $v1['cate'],
                            'id' => $v1['stockId'],
                        );
                        $res = $this->mGoods->where(array('goods_id' => $v1['stockId']))->find();
                        if ($res) {
                            $this->mGoods->save($info);
                        } else {
                            $this->mGoods->add($info);
                        }
                        $str .= $v1['stockId'] . ',';

                        //记录cateid
                        $temp_cate_id=$v1['cate'];
                    }
                }
                // echo $str;
               $goodsIds = substr($str, 0, strlen($str) - 1);
               $goodsIds = '('.$goodsIds.')';
               // echo $goodsIds;
               // die();
                //把没有返回的菜品全部不显示 show 0不显示 1显示
                // $this->mGoods->where(array('goods_id',array('not in',$goodsIds)))->setField('show',0);
                $this->mGoods->where( " cate=$temp_cate_id and goods_id not in $goodsIds")->setField('cut_off',1);
//                echo $this->mGoods->getLastSql();
                //删除原来的每周菜单关系
                $this->mWeekRelation->where(array('window_id'=>$key))->delete();

                //添加最新一周菜单
                foreach ($data['data'] as $k => $v) {
                    foreach ($v as $k1 => $v1) {
                        $week = array(0,1, 2, 3, 4, 5, 6, 7);
                        $arr = array();
                        foreach ($week as $k2 => $v2) {
                            $arr[$k2]['week'] = $v2;
                            $arr[$k2]['res_id'] = $this->resId;
                            $arr[$k2]['goods_id'] = $v1['stockId'];
                            $arr[$k2]['window_id'] = $key;
                        }
                        $this->mWeekRelation->addAll($arr);
                    }
                }
            }
        }
    }
    /**
     * 更新菜品信息  接收
     */
    public function updateGoods()
    {
//        $data = json_decode(file_get_contents("php://input"), true);
        // $data = $this->_request();
        // $sign = $this->doSign($data['type']);
        // wLog(date('Y-m-d H:i:s').'data:'.var_export($data,true),'restaurantstyy');
        // if ($sign != $data['sign']) {
        //     $this->ajaxReturn(array('code' => 201, 'message' => '签名错误'));
        // }
        // $ids =  $this->mRestaurantInfo->where(array('cut_off'=>0,'res_id'=>$this->resId))->getField('restaurant_id',true);
        // $ids = implode(',',$ids);
//        $data = json_decode(file_get_contents("php://input"), true);
        $type = $this->_request('type');
        $ids = '30';
        $windows = $this->mWindow->where(array('cut_off'=>0,'restaurant_id'=>$ids))->getField('id,window_id');
        $time = date('Y-m-d',time());

        if($type==1){
            $this->doWindow($ids);
        }else if($type==2){
            $window = implode(',',$windows);
            $this->doCategory($ids,$window);
        }else{
            $types = 1;
            $this->doGoods($ids,$windows,$time,$types);
        }
        $this->ajaxReturn(array('code' => 200, 'message' => '成功'));
    }
    /**
     * @param $params 参数
     * 验证接收的签名
     */
    public function doSign($param){
        $signStr = $param.'golivecc';
        return md5($signStr);
    }


    /**
     * 上传订单信息给校联
     */
    public function upload()
    {
        $styApi = Service("RestaurantStyy/BaseRestaurantApi");
        $mOrder = D('Base/RestaurantstyyOrder');
        $orders = $mOrder->where(array('upload' => 0,'status' => array('in','1,2'),'is_pay_notify' => 1))
            ->getField('order_id', true);
        if ($orders) {
            foreach ($orders as $k => $v) {
                $res = $styApi->sendOrder($v);
                if($res==1){
                    $mOrder->where(array('order_id'=>$v))->setField('upload',1);
                }
            }
        }
    }
}